<?php
declare (strict_types = 1);

namespace app\admin\controller;

use think\response\Json;
use app\common\model\Region as RegionModel;
/**
 * 省市区数据
 * Class Region
 * @package app\admin\controller
 */
class Region extends Controller
{
    /**
     * 列表
     * @return Json
     */
    public function lists(): Json
    {
        $model = new RegionModel;
        $list = array_values($model->getCacheAll());
        return $this->renderSuccess(['items'=>$list]);
    }
    /**
     * 树
     * @return Json
     */
    public function citytrees(): Json
    {
        $model = new RegionModel;
        $list = array_values($model->getCacheTree());
        foreach ($list as &$item) {
            if(isset($item['children']) && is_array($item['children']) ){
                $item['children'] = array_values($item['children']);
                foreach ($item['children'] as &$child) {
                    if(isset($child['children']) && is_array($child['children']) ){
                        unset($child['children']);
                    }
                }
            }
        }
        return $this->renderSuccess($list);
    }
    /**
     * 树
     * @return Json
     */
    public function regiontrees(): Json
    {
        $model = new RegionModel;
        $list = array_values($model->getCacheTree());
        foreach ($list as &$item) {
            if(isset($item['children']) && is_array($item['children']) ){
                $item['children'] = array_values($item['children']);
                foreach ($item['children'] as &$child) {
                    if(isset($child['children']) && is_array($child['children']) ){
                        $child['children'] = array_values($child['children']);
                    }
                }
            }
        }
        return $this->renderSuccess($list);
    }

    /**
     * 添加
     * @return Json
     */
    public function add(): Json
    {
        $model = new RegionModel;
        if ($model->add($this->postForm())) {
            return $this->renderSuccess('添加成功');
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 编辑
     * @param int $id
     * @return Json
     */
    public function edit(int $id): Json
    {
        $model = RegionModel::detail($id);
        if ($model->edit($this->postForm())) {
            return $this->renderSuccess('更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 删除
     * @param int $id
     * @return Json
     */
    public function delete(int $id): Json
    {
        $model = RegionModel::detail($id);
        if (!$model->delete()) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }
}
